/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-06-02 15:18:47
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-06-18 17:39:51
 */
import type { OnMessageCallback } from 'mqtt'
import { useCommonStore } from '@/stores/common'
const { PublicMqtt } = useCommonStore()
export default function useMqtt() {
	const startMqtt = (val: string, callback: OnMessageCallback) => {
		nextTick(() => {
			//初始化mqtt
			PublicMqtt.init()
			//链接mqtt
			PublicMqtt.link(val)
			getMessage(callback)
		})
	}
	const getMessage = (callback: OnMessageCallback) => {
		PublicMqtt?.get(callback)
	}
  const doPublish = (topic, payload) => {
		PublicMqtt?.doPublish(topic, payload)
	}
	const doUnSubscribe = () => {
		//页面销毁结束订阅
		if (PublicMqtt) {
			PublicMqtt.doUnSubscribe()
		}
	}
	onUnmounted(() => {
		// doUnSubscribe()
	})

	return {
		startMqtt,
    doPublish,
		doUnSubscribe,
	}
}
